package com.hison.handler.security;

import com.alibaba.fastjson.JSON;
import com.hison.enums.AppHttpCodeEnum;
import com.hison.util.ResponseResult;
import com.hison.util.WebUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ClassName: AuthenticationEntryPointImpl
 * @Descripiton: 自定义认证失败的处理器。ResponseResult、AppHttpCodeEnum是我们在huanf-framework工程写的类
 * @Author: 小郑
 * @Date： 2024/1/13 13:57
 * @Version：1.8
 **/
@Configuration
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        //打印异常信息
        e.printStackTrace();
        //判断是登录才出现异常(返回'用户名或密码错误')，还是没有登录就访问特定接口才出现的异常(返回'需要登录后访问')，还是其它情况(返回'出现错误')
        ResponseResult result = null;
        if(e instanceof BadCredentialsException){
            //第一个参数返回的是响应码，AppHttpCodeEnum是我们写的实体类。第二个参数是返回具体的信息
            result = ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_ERROR.getCode(),e.getMessage());
        } else if(e instanceof InsufficientAuthenticationException){
            //第一个参数返回的是响应码，AppHttpCodeEnum是我们写的实体类
            result = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        } else {
            //第一个参数返回的是响应码，AppHttpCodeEnum是我们写的实体类。第二个参数是返回具体的信息
            result = ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR.getCode(),"认证或授权失败");
        }
        //响应给前端
        WebUtils.renderString(response, JSON.toJSONString(result));

    }
}